package com.htgd.gardenexpo.controller;

import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConSocialContent;
import com.htgd.gardenexpo.entity.GeConSocialContentReview;
import com.htgd.gardenexpo.service.IGeConSocialContentReviewService;
import com.htgd.gardenexpo.service.IGeConSocialContentService;
import com.htgd.gardenexpo.vo.Config;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;

@RestController
@RequestMapping("/api/wxUtil")
@Api( tags = "微信工具")
@Slf4j
public class WxUtilController {

    @Value("${wx.public.appId}")
    public String appId;

    @Value("${wx.public.appsecret}")
    public String appsecret;

    private static final String TOKEN = "yuhuaxian"; // 在微信公众平台设置的Token

    @Autowired
    private IGeConSocialContentReviewService geConSocialContentReviewService;

    @Autowired
    private IGeConSocialContentService geConSocialContentService;




    @GetMapping("/receive")
    @ApiOperation("接收验证")
    public void  receive(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        // 验证签名
        if (verifySignature(signature, timestamp, nonce)) {
            // 验证通过，返回echostr
            response.getWriter().write(echostr);
        } else {
            response.getWriter().write("failed");
        }

    }

    @PostMapping ("/receive")
    @ApiOperation("接收内容")
    public void  receiveMsg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");

        // 验证签名
        if (verifySignature(signature, timestamp, nonce)) {
            // 读取请求体中的JSON消息
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            String jsonMessage = sb.toString();
            JSONObject jsonObject = JSONObject.parseObject(jsonMessage);
            try {
                JSONObject result = jsonObject.getJSONObject("result");
                String traceId = jsonObject.getString("trace_id");
                String suggest = result.getString("suggest");
                GeConSocialContentReview one = geConSocialContentReviewService.lambdaQuery().eq(GeConSocialContentReview::getTraceId, traceId).one();
                if("pass".equals(suggest)){
                    geConSocialContentReviewService.lambdaUpdate().eq(GeConSocialContentReview::getTraceId,traceId)
                            .set(GeConSocialContentReview::getStatus,"1").update();

                    //检查是否所有都已经通过
                    boolean exists = geConSocialContentReviewService.lambdaQuery().eq(GeConSocialContentReview::getContentId, one.getContentId())
                            .ne(GeConSocialContentReview::getStatus, "1").exists();
                    if(!exists){
                        geConSocialContentService.lambdaUpdate().eq(GeConSocialContent::getId,one.getContentId())
                                        .set(GeConSocialContent::getStatus,"1").update();
                    }

                }else {
                    geConSocialContentReviewService.lambdaUpdate().eq(GeConSocialContentReview::getTraceId,traceId)
                            .set(GeConSocialContentReview::getStatus,"2").update();

                    geConSocialContentService.lambdaUpdate().eq(GeConSocialContent::getId,one.getContentId())
                            .set(GeConSocialContent::getStatus,"2").update();
                }
                System.out.println("返回的的消息: " + jsonObject);
                response.getWriter().write("success");
            } catch (Exception e) {
                e.printStackTrace();
                response.getWriter().write("{\"error\": \"解密失败\"}");
            }
        } else {
            response.getWriter().write("{\"error\": \"签名验证失败\"}");
        }

    }

    // SHA1签名验证
    private boolean verifySignature(String signature, String timestamp, String nonce) {
        // 将参数按字典顺序排序
        String[] arr = new String[]{TOKEN, timestamp, nonce};
        Arrays.sort(arr);

        // 拼接成一个字符串
        StringBuilder sb = new StringBuilder();
        for (String str : arr) {
            sb.append(str);
        }

        String sha1 = sha1(sb.toString());
        return sha1.equals(signature);
    }

    // SHA1加密
    private String sha1(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] bytes = md.digest(str.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : bytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException("SHA1加密失败", e);
        }
    }




}
